package org.upfrost.testutil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;

import javax.sql.DataSource;

public class JdbcCall 
{
	private javax.sql.DataSource m_datasource;
	private Connection m_conn;
	private ResultSet results = null;
	private PreparedStatement m_stmt = null;
	
	public JdbcCall(DataSource ds)
	{
		m_datasource = ds;
	}

	public JdbcCall open(String query) throws SQLException
	{
		if (m_stmt != null)
			m_stmt.close();
		
		m_conn = m_datasource.getConnection();
		m_stmt = m_conn.prepareStatement(query);
		
		return this;
	}

	public JdbcCall params(Object... objs) throws SQLException
	{
		for (int index = 0; index < objs.length; index++)
		{
			setParameter(m_stmt, index+1, objs[index]);
		}
		
		return this;
	}

	public ResultSet execute() throws SQLException
	{
		return m_stmt.executeQuery();
	}

	public int update() throws SQLException
	{
		return m_stmt.executeUpdate();
	}

	public void close() throws SQLException
	{
		m_stmt.close();
		m_conn.close();
	}
	
	private void setParameter(PreparedStatement stmt, int col, Object el) throws SQLException
	{
		if (el instanceof java.lang.Integer)
			stmt.setInt(col, ((Integer)el).intValue());
		else if (el instanceof java.lang.String)
			stmt.setString(col, (String)el);
		else if (el instanceof java.lang.Long)
			stmt.setLong(col, ((Long)el).longValue());
		else if (el instanceof java.lang.Float)
			stmt.setFloat(col, ((Float)el).floatValue());
		else if (el instanceof java.lang.Double)
			stmt.setDouble(col, ((Double)el).doubleValue());
		else
			stmt.setObject(col, el);
	}

}
